package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

   // @Autowired
  //  private UserService userService;

    //@Autowired
    //private AddressBookService addressBookService;


    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("提交成功");

    }

    @GetMapping("/page")
        public R<Page>page(int page,int pageSize,String number){
        Page<Orders>pageinfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageDto = new Page<>();

        //Orders orders = ordersService.getById(number);

        //从order表查询订单号为number的订单
        LambdaQueryWrapper<Orders>ordersLambdaQueryWrapper=new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number!=null,Orders::getNumber,number);
        ordersLambdaQueryWrapper.orderByAsc(Orders::getOrderTime);
        ordersService.page(pageinfo, ordersLambdaQueryWrapper);

        //为DTO赋值
        BeanUtils.copyProperties(pageinfo,pageDto,"records");

        //为每条数据赋值
        List<Orders> ordersList = pageinfo.getRecords();
        List<OrdersDto>ordersDtoList = ordersList.stream().map((order)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);

            LambdaQueryWrapper<OrderDetail>orderDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,order.getId());
            ordersDto.setOrderDetails(orderDetailService.list(orderDetailLambdaQueryWrapper));



            return ordersDto;
        }).collect(Collectors.toList());

        pageDto.setRecords(ordersDtoList);
        return R.success(pageDto);
    }


}
